<template>
  <!--  工装-->
  <div class="content">
    <div class="pageSearchView">
      <el-form :inline="true" :model="searchParam" class="demo-form-inline">
        <el-form-item label="机台">
          <el-select v-model="searchParam.id" clearable filterable placeholder="请选择机台" style="width: 250px"
            @change="idChange">
            <el-option v-for="item in storageOutList" :key="item.id" :label="item.equipmentName" :value="item.id">
              <span style="float: left">{{ item.equipmentName }}</span>
              <span style="
                    float: right;
                    color: var(--el-text-color-secondary);
                    font-size: 13px;
                  "> {{ item.equipmentCode }} </span>
            </el-option>
          </el-select>
        </el-form-item>
        <!--        <el-form-item>-->
        <!--          <el-button type="primary" :icon="Search" @click="getList()">查询</el-button>-->
        <!--          <el-button class="refreshBtn" :icon="Refresh" @click="resetSearch()">重置</el-button>-->
        <!--        </el-form-item>-->
      </el-form>
    </div>
    <div class="pageTableView">
      <div class="pageTableMenuView">
        <div class="pageTableTitle">
          <div>工装信息区</div>
        </div>
        <div class="pageTableButView">
          <el-button @click="handleAdd(1)" type="primary" :icon="Plus" :disabled="!searchParam.id">上工</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <el-table :data="paginatedData" height="400px" row-key="id" :stripe="false" class="sort-el-table"
        header-cell-class-name="witheTableHeader">
        <el-table-column label="序号" type="index" align="center" width="70" />
        <el-table-column prop="toolRegisterCode" min-width="150" label="工装编码" align="center" />
        <el-table-column prop="registerName" min-width="200" label="工装名称" align="center" />
        <el-table-column prop="toolingName" min-width="200" label="工装类型" align="center" />
        <el-table-column prop="toolingAttributes" min-width="100" label="工装属性" align="center"
          :formatter="toolingAttributesFormatter" />
        <el-table-column label="操作" align="center" width="200">
          <template #default="scope">
            <el-button plain size="small" :icon="Switch" @click="handleAdd(2, scope.row)"> 更换 </el-button>
            <el-button type="danger" plain size="small" :icon="Delete" @click="handleConfigDelete(scope.row)"> 下工
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pageTableView">
      <div class="pageTableMenuView">
        <div class="pageTableTitle">
          <div>工装更换记录</div>
        </div>
      </div>
      <!-- 表格 -->
      <el-table :data="changeData" height="400px" row-key="id" :stripe="false" class="sort-el-table"
        header-cell-class-name="witheTableHeader">
        <el-table-column label="序号" type="index" align="center" width="70" />
        <el-table-column prop="toolRegister.toolRegisterCode" min-width="150" label="工装编码" align="center" />
        <el-table-column prop="toolRegister.registerName" min-width="200" label="工装名称" align="center" />
        <el-table-column prop="basedataTooling.name" min-width="200" label="工装类型" align="center" />
        <el-table-column prop="basedataTooling.toolingAttributes" min-width="100" label="工装属性" align="center"
          :formatter="toolingAttributesFormatter" />
        <el-table-column label="上次更换时间" prop="tooUpdateTime" min-width="200" align="center" />
      </el-table>
    </div>
    <!-- 编辑/新建弹框 -->
    <el-dialog v-model="showCrud" :title="crudTitle" width="1000px" top="5vh">
      <el-form>
        <el-form-item label="工装类型">
          <el-select v-model="toolingType" filterable style="width: 300px;margin-bottom: 10px;" :disabled="isChange"
            placeholder="请选择工装类型" @change="toolingTypeChange">
            <el-option v-for="item in toolingTypeList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <el-table :data="toolingList" row-key="id" class="sort-el-table" header-cell-class-name="witheTableHeader"
        style="width:100% " height="400px" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" :selectable="selectable" />
        <el-table-column label="序号" type="index" align="center" width="70" />
        <el-table-column prop="toolRegisterCode" min-width="150" label="工装编码" align="center" />
        <el-table-column prop="registerName" min-width="200" label="工装名称" align="center" />
        <el-table-column prop="toolingName" min-width="200" label="工装类型" align="center" />
        <el-table-column prop="toolingAttributes" min-width="100" label="工装属性" align="center"
          :formatter="toolingAttributesFormatter" />
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCrud = false">取消</el-button>
          <el-tooltip placement="top" :content="tooltipContent" :disabled="!isButtonDisabled">
            <el-button type="primary" @click="handleSave" :disabled="selectedRows.length !== 1">保存</el-button>
          </el-tooltip>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { ref, computed, watch, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axiosInstance from "@/utils/http/api";
import {
  Delete, Edit, Tickets, DocumentChecked, Switch
  , Search, Share, Upload, Refresh, Plus, DocumentCopy, Files, Rank, Calendar
} from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import { equipmentAll } from '@/api/scheduling/dispatchManagement'

const paginatedData = ref([])//列表数据
const changeData = ref([])//更换记录
const searchParam = ref({})
const formData = ref({});
const procedureOrderList = ref({})
const toolingTypeList = ref([])
const toolingType = ref('')
const storageOutList = ref({})

const toolingList = ref([])

const getOption = () => {
  equipmentAll().then(res => {
    console.log(res, 'equipmentAll')
    storageOutList.value = res.data
  })

  axiosInstance.post('/api/basedataTooling/getAll').then(res => {
    toolingTypeList.value = res.data
  })
  // toolingTypeList

}

const toolingRow = ref({})

const toolingTypeChange = (e) => {
  for (const item of toolingTypeList.value) {
    if (item.id == e) {
      toolingRow.value = item
    }
  }
  // api/toolRegister/getToolRegister?toolingId=0149ab69315e8bfd14ed8cab95cb64e1
  axiosInstance.get('/api/toolRegister/getToolRegister', {
    params: {
      toolingId: e
    }
  }).then(res => {
    const list = res.data
    for (const item of list) {
      item.toolingAttributes = toolingRow.value.toolingAttributes
      item.toolingName = toolingRow.value.name
    }
    toolingList.value = res.data
  })
}

const idChange = (e) => {
  if (e) {
    getList()
  } else {
    paginatedData.value = []
  }
}
const attributesOptions = ref([
  {
    label: '工装',
    value: "1"
  }, {
    label: '模具',
    value: "2"
  }, {
    label: '检具',
    value: "3"
  }, {
    label: '刀具',
    value: "4"
  }
])


const toolingAttributesFormatter = (e) => {
  if (e.basedataTooling) {
    const attribute = attributesOptions.value.find(option => option.value == e.basedataTooling.toolingAttributes);
    return attribute ? attribute.label : '';
  }else{
    const attribute = attributesOptions.value.find(option => option.value == e.toolingAttributes);
    return attribute ? attribute.label : '';
  }
  

}

const selectedRows = ref([]);

// ... 其他数据和方法

function handleSelectionChange(selection) {
  selectedRows.value = selection;
}


const showCrud = ref(false); // 编辑/新建弹框

const transferType = ref({ transferType: 'pick' })
import { useRouter, useRoute } from 'vue-router';

const route = useRoute();
const router = useRouter();
const isChange = ref(false)
const crudTitle = ref('上工')
const rowValue = ref({})
// 新建记录
const handleAdd = (e, row) => {
  isChange.value = false
  crudTitle.value = '上工'
  if (e == 2) {
    rowValue.value = row
    // 有行内数据 是更换工装
    crudTitle.value = '更换工装'
    toolingType.value = row.toolId
    toolingTypeChange(row.toolId)
    isChange.value = true
  }

  // form
  // Data.value = {}
  // axiosInstance.post("/api/toolRegister/getAll", {}).then(res => {
  //   toolingList.value = res.data
  // })
  showCrud.value = true
};

const selectable = (row) => {
  // console.log(row)
  let rVal = true
  for (const item of paginatedData.value) {
    if (item.toolRegisterId == row.id) {
      rVal = false
    }
  }
  return rVal
  // toolRegisterId row.id
}

const handleConfigChange = (e) => {
  // 更换工装
}

const handleConfigDelete = (e) => {
  ElMessageBox.confirm('是否确认下工?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      axiosInstance.post('/api/toolEquipment/deleteToolEquipment', {
        id: e.id
      })
        .then(res => {
          if (res.code !== 200) {
            ElMessage.error(res.message);
            return false
          }
          getList()
        });
    })
}

// 保存记录
const handleSave = async () => {
  const param = []

  for (const item of selectedRows.value) {
    param.push({
      equipmentId: searchParam.value.id,
      toolId: toolingType.value,
      toolRegisterId: item.id
    })
  }
  // {
  //   equipmentId: route.query.id,
  //   toolId: null,
  //   toolRegisterId: null
  // }
  if (isChange.value) {
    param[0].id = rowValue.value.id
    axiosInstance.post("/api/toolEquipment/updateTool", param[0])
      .then((res) => {
        if (res.code !== 200) {
          ElMessage.error(res.message)
          return false
        }
        showCrud.value = false;
        getList();
      })
  } else {
    axiosInstance.post("/api/toolEquipment/saveBatch", param)
      .then((res) => {
        if (res.code !== 200) {
          ElMessage.error(res.message)
          return false
        }
        showCrud.value = false;
        getList();
      })
  }

};

// 获取列表
const getList = async () => {
  axiosInstance.post('/api/toolEquipment/getAll', { equipmentId: searchParam.value.id })
    .then(res => {
      if (res.code !== 200) {
        ElMessage.error(res.message);
        return false
      }
      paginatedData.value = res.data
      // pageTotal.value = res.data.total;
    });

  axiosInstance.post('/api/toolRegisterUpdateLog/queryUpdateLog', { equipmentId: searchParam.value.id })
    .then(res => {
      if (res.code !== 200) {
        ElMessage.error(res.message);
        return false
      }
      changeData.value = res.data
      // pageTotal.value = res.data.total;
    });
};


const isButtonDisabled = computed(() => selectedRows.value.length !== 1);

const tooltipContent = computed(() => {
  return isButtonDisabled.value ? '请进行单条操作' : '';
});


onMounted(() => {
  // getList();
  getOption();
});
</script>
<style scoped lang="scss"></style>
